<template>
  <CDialog
    :title="title"
    v-model:visible="dialogVisible"
    :loading="loading"
    confirmText="保存"
    cancelText="关闭"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
  >
    <el-form ref="formRef" :model="localFormModel" label-position="top">
      <el-row :gutter="20">
        <template v-for="(item, index) in props.schema" :key="index">
          <el-col :span="item.span || 24" v-if="handleIsShow(item?.colShow)">
            <el-form-item
              :label="item.label"
              :prop="item.field"
              :rules="
                isFunction(rules[item.field])
                  ? rules[item.field]({ values: localFormModel })
                  : rules[item.field]
              "
              v-if="handleIsShow(item?.show)"
            >
              <!-- <FormItem :schema="item" :localFormModel="localFormModel"></FormItem> -->
              <template v-if="item.component === 'CDosageAndUnit' && isArray(item.fields)">
                <CDosageAndUnit
                  v-model:dosage="localFormModel[item.field]"
                  v-model:unit="localFormModel[item.fields[0]]"
                  :placeholder="getPlaceholder(item)"
                ></CDosageAndUnit>
              </template>
              <component
                :is="item.component"
                v-model="localFormModel[item.field]"
                :placeholder="getPlaceholder(item)"
                v-bind="item.componentProps"
                v-else-if="isString(item.field)"
              >
                <template v-if="item?.options?.length">
                  <template v-if="item.component === 'ElRadioGroup'">
                    <el-radio v-for="opt in item.options" :key="opt.value" :label="opt.value"
                      >{{ opt.label }}
                    </el-radio>
                  </template>
                  <template v-else-if="item.component === 'ElSelect'">
                    <el-option
                      v-for="opt in item.options"
                      :key="opt.value"
                      :label="opt.label"
                      :value="opt.value"
                    />
                  </template>
                </template>
                <template #append v-if="item.isRate">%</template>
              </component>
            </el-form-item>
          </el-col>
        </template>
      </el-row>
    </el-form>
  </CDialog>
</template>

<script lang="ts" setup name="CFormDialog">
import {
  withDefaults,
  defineProps,
  defineEmits,
  defineExpose,
  computed,
  watch,
  reactive,
  ref
} from 'vue';
import { CDialog } from '@/components/CDialog';
import CDosageAndUnit from '@/businessComponents/CDosageAndUnit/index.vue';
import { addStageFlow, editStageFlow } from '@/apis/pcf/myModel/modelDetail';
import type {
  ProcessDataItem,
  AddStageFlowParams,
  EditStageFlowParams
} from '@/apis/pcf/myModel/model/modelDetailModel';
import { useMessage } from '@/hooks/useMessage';
import type { FormSchema, MaterialDialogOperationType } from './form-dialog';
import FormItem from './form-item.vue';

import { isString, isArray, isFunction, isBoolean } from '@/utils/is';
// eslint-disable-next-line no-undef
const formModel = reactive<Recordable>({});

const rules = ref<any>({});

function setFormModel() {
  console.log('setFormModel', props.schema);
  for (let i in props.schema) {
    const item = props.schema[i];
    // formModel[item.field] = item.defaultValue ?? '';
    // if (item.fields?.length) {
    //   for (let j in item.fields) {
    //     formModel[item.fields[j]] = item.defaultValueObj
    //       ? item.defaultValueObj[item.fields[j]]
    //       : '';
    //   }
    // }
    // 必填项
    if (item.required) {
      rules.value[item.field] = [
        {
          required: true,
          message: '必填项',
          trigger: ['submit', 'blur', 'change']
        }
      ];
    }
    // 动态校验规则
    if (item.dynamicRules) {
      rules.value[item.field] = item.dynamicRules;
    }
  }
}

interface MaterialDialogProps {
  visible: boolean;
  processNo?: string;
  modelNo?: string;
  flowItem?: ProcessDataItem;
  schema: FormSchema[];
  // eslint-disable-next-line no-undef
  formModel: Recordable;
  // eslint-disable-next-line no-undef
  submitFn: (formModel: Recordable) => Promise<boolean>;
}
const props = withDefaults(defineProps<MaterialDialogProps>(), {});
const emits = defineEmits(['update:visible', 'update:formModel']);
const { createMessage } = useMessage();
const dialogVisible = computed({
  get: () => {
    return props.visible;
  },
  set: (value: boolean) => {
    emits('update:visible', value);
  }
});
watch(
  () => dialogVisible.value,
  val => {
    if (val) {
      init();
      setFormModel();
    }
  }
);

const localFormModel = computed({
  get: () => {
    return props.formModel;
  },
  // eslint-disable-next-line no-undef
  set: (value: Recordable) => {
    emits('update:formModel', value);
  }
});

const formRef = ref();
const loading = ref(false);

/**
 * 表单内容
 */
const formState = reactive({
  dataType: '',
  nodeName: '',
  dosage: '',
  unit: 'pcs',
  remark: ''
});

/**
 * 操作类型
 */
const operationType = ref<MaterialDialogOperationType>();

/**
 * 弹窗标题
 */
const title = computed(() => {
  return operationType.value === 'ADD' ? '新增物料信息' : '编辑物料信息';
});

/**
 * 初始化
 */
function init() {
  if (props.processNo) {
    operationType.value = 'ADD';
  } else {
    operationType.value = 'EDIT';
  }
}

/**
 * 保存按钮
 */
function handleConfirm() {
  console.log('handleConfirm');
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      submitFlowReq();
    }
  });
}

/**
 * 接口请求
 */
async function submitFlowReq() {
  console.log('submitFlowReq');
  loading.value = true;
  try {
    if (props.submitFn) {
      await props.submitFn(formModel.value);
      dialogVisible.value = false;
      createMessage.success(operationType.value === 'ADD' ? '新增成功！' : '编辑成功！');
      loading.value = false;
    } else {
      loading.value = false;
      throw new Error('没有submitFn prop!');
    }
  } catch (error) {
    console.log('error', error);
    loading.value = false;
  }
}

/**
 * 是否显示(show、colShow相同处理方式)
 * 默认一直展示
 */
function handleIsShow(isShow: FormSchema['show']) {
  if (isBoolean(isShow)) {
    return !!isShow;
  } else if (isShow && isFunction(isShow)) {
    return isShow({ values: localFormModel.value });
  } else {
    return true;
  }
}

/**
 * 获取placeholder
 */
function getPlaceholder(item: FormSchema) {
  if (item.componentProps?.placeholder) {
    return item.componentProps.placeholder as string;
  }
  return item.component === 'ElInput' || item.component === 'CDosageAndUnit' ? '请输入' : '请选择';
}

function resetFields() {
  console.log('resetFields');
  formRef.value?.resetFields();
}

function updateSchema() {
  console.log('updateSchema');
  setFormModel();
}

defineExpose({
  resetFields,
  updateSchema
});
</script>

<style lang="scss">
@use '../styles/form-dialog.scss' as *;
</style>
